<%@page import="java.util.Arrays"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>人机大战之成语接龙</title>
    <style>
        h1{
            color:red;
        }
        input{
            padding: 8px;
            border-radius: 6px;
        }
        .history{
            min-height: 100px;
            border: 1px solid gray;
            border-radius: 8px;
            padding: 10px;
        }
        form >div:nth-child(2) {
            display: flex;
            gap: 10px;
        }
        .msg{
            color:red;
            font-weight: bold; /* 字体加粗 */
            margin: 10px 0;
        }
    </style>
</head>
<body><%
    request.setCharacterEncoding("utf-8");//对POST的数据，必须设置数据的编码
    String cy=request.getParameter("cy");
    String history=request.getParameter("history");
    if(history==null)history="";
    out.print(cy+"\t"+history);
    String msg="";
    String first="";
    boolean iswin=false;
    if(cy!=null){ //提交有数据，需要处理用户输入的数据
        // ...处理过程
        cy=cy.trim();
        Class.forName("com.mysql.cj.jdbc.Driver");
        try(Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","12qwas");
            PreparedStatement ps=cn.prepareStatement("select * from chengyu where cy=?")
        ){
            ps.setString(1,cy);
            try (ResultSet rs = ps.executeQuery();) {
                //ctrl+alt+v
                if (rs.next()) {//用户输入的是成语
                    history += "," + cy;//用户输入的成语放到接龙历史中
                    first = cy.substring(cy.length() - 1);

                } else {//用户输入的不是成语
                    msg = "你输入的“" + cy + "”不是成语";
                    first=cy.substring(0,1);//用户下次输入时成语的首字
                }
            }
        }
        if(msg.length()==0){
            try(Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","12qwas");
                PreparedStatement ps=cn.prepareStatement("select cy from chengyu where first=? order by rand() limit 1")
            ){
                ps.setString(1,first);
                try (ResultSet rs = ps.executeQuery();) {
                    //ctrl+alt+v
                    if (rs.next()) {
                        cy=rs.getString("cy");
                        history += "," + cy;
                        first = cy.substring(cy.length() - 1);

                    } else {//用户输入的不是成语
                        msg = "恭喜你在成语接龙游戏中战胜了计算机";
                        iswin = true;
                    }
                }
            }
        }
    }
%>
<div class='kuang'>
    <h1>人机大战之成语接龙</h1>
    <div class='history'>
        <%
            String[] cys=history.split(",");
//out.print(Arrays.toString(cys));
            for(int i=1; i<cys.length;++i){
                out.println("\t\t<p>"+i+". ["+(i%2==0?"机":"人")+"] "+cys[i]+"</p>");
            }
        %>
    </div>
    <form method="post" action="">
        <div class='msg'><%=msg%></div>
        <div>
            <input type='text' name='cy' <%=iswin?" disabled":""%> />
            <input type="submit" value='提交' onclick='return check()' <%=iswin?" disabled":""%>/>
            <input type="button" value='重新开始' onclick='return again()'/>
            <input type='hidden' name='history' value='<%=history%>' />
        </div>
    </form>
</div>
<script>
    const $=function(selector){ //根据选择器返回指定的首个对象
        return document.querySelector(selector)
    }
    function again(){
        location.href=""
    }
    function check(){ //对用户输入的成语进行规则校验
        //函数返回true，表单会提交，若返回false，就不会提交
        let first='<%=first%>' //用户接龙成语的首字
        let cy=$('input[name=cy]').value.trim() //获取用户输入的成语, 清除两端的空白
// 	if(cy.length<3||cy.length>14){ //成语长度不正确
// 		$('.msg').innerText='成语的长度应该有3~14汉字~'
// 		return false
// 	}
// 	if(!cy.startsWith(first)){
// 		$('.msg').innerText='输入的成语必须以“关”字开头~'
// 		return false
// 	}
        try{
            if(cy.length<3||cy.length>14) throw new Error('成语的长度应该有3~14汉字~') //抛出异常后会转移到catch块去执行，try块后续的代码不会再执行
            if(!cy.startsWith(first)) throw new Error('输入的成语必须以“<%=first%>”字开头~')//try块若没有异常，catch块也不会执行
            return true
        }catch(e){
            $('.msg').innerText=e.message //将错误信息显示在界面上
            return false //不再提交表单
        }
    }
</script>
</body>
</html>
